package com.heima.search.service.Impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
//import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
//import com.heima.utils.thread.ApThreadLocal;
import com.heima.utils.thread.ApThreadLocal;
import com.mongodb.client.result.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存历史记录
     *
     * @param keywords
     * @param userId
     */
    @Override
    @Async//执行异步方法
    public void addHistoryToMongoDB(String keywords, Integer userId) {
        //1.根据关键字和用户ID查询搜索记录是否存在
        Query query=Query.query(
                Criteria.where("keyword").in(keywords).and("userId").is(userId)
        );
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        //2.如果存在，则更新当前数据的时间为最新时间
        if(apUserSearch!=null){
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }
        //重新封装数据
        apUserSearch=new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keywords);
        apUserSearch.setCreatedTime(new Date());


        //3.如果不存在, 我们要根据用户id去查询所有的mongo记录，查看返回值数据是否超过10条
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(
                Query.query(
                        Criteria.where("userId").is(userId)
                ).with(Sort.by(Sort.Direction.DESC,"createdTime")),
                ApUserSearch.class
        );
        //如果不超过10条，则直接插入
        if(apUserSearchList!=null && apUserSearchList.size()<10){
            mongoTemplate.insert(apUserSearch);
        }else{
            //如果超过10条，则替换最早的那一条
                //先获取最久的那一条
            ApUserSearch lastApUserSearch = apUserSearchList.get(apUserSearchList.size() - 1);
            /**
             * 执行替换操作findAndReplace 表示查询并替换
             * 参数1表示 根据最后一条的id去查询条件，得到的是老数据
             * 参数2表示最新数据
             */
            mongoTemplate.findAndReplace(Query.query(Criteria.where("_id").is(lastApUserSearch.getId())), apUserSearch);
        }
    }

    /**
     * 加载历史记录
     *
     * @return
     */
    @Override
    public ResponseResult loadHistory() {
    //获取用户id
        ApUser apUser = ApThreadLocal.getApUser();
        if(apUser==null && apUser.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据条件查询mongo
        Query query=Query.query(
                Criteria.where("userId").is(apUser.getId())
        );
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearchList);
    }

    /**
     * 删除历史记录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delHistory(HistorySearchDto dto) {
        if(dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = ApThreadLocal.getApUser();
        if(apUser.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        Query query=Query.query(
                Criteria.where("_id").is(dto.getId()).and("userId").is(apUser.getId())
        );
        DeleteResult result = mongoTemplate.remove(query, ApUserSearch.class);
        boolean flag = result.wasAcknowledged();
        return ResponseResult.okResult(flag?"删除成功":"删除失败");
    }
}
